# -*- coding: utf-8 -*-
from __future__ import print_function, division
#系统库
import json
#第三方库
import tornado.websocket
import tornado.web
import tornado.template
#自定义库
import AGOTlib
import functions
import database
import hall
import local

#主体
logger = AGOTlib.logging.getLogger('AGOT')

class AGOTWebSocket(tornado.websocket.WebSocketHandler):
    current_socket_id = 0
    def __init__(self,application, request, **kwargs):
        tornado.websocket.WebSocketHandler.__init__(self,application, request, **kwargs)
        self.socket_id = 0
        self.command_map = {}
        self.command_map[1] = self.on_login
        self.command_map[2] = self.on_register
        self.remote_ip = request.remote_ip;
        
    def allow_draft76(self):
        # for iOS 5.0 Safari
        return True
        
    def open(self):
        AGOTWebSocket.current_socket_id = AGOTWebSocket.current_socket_id + 1 
        self.socket_id = AGOTWebSocket.current_socket_id
        logger.debug('['+self.remote_ip+']  connected')

        

    def on_message(self, message):
        logger.debug('['+self.remote_ip+']  <'+message)
        item = json.loads(message)
        func = self.command_map.get(item['command'])
        if func != None:
            func(item)
        
    def on_login(self , item):
        ret = game.core.userLogin( item['username'] , item['password'] , self.socket_id , self)
        if ret > 0:
            string = "{id:"+str(ret) +",name:\""+ item['username']+ "\",errormsg:\"\"}"
            self.write_message(string)
        elif ret == 0:
            #密码错误
            string = "{id: -1 ,errormsg:\""+ local.String.SKT_LG_ER_usernamepassword+"\"}"
            self.write_message(string)
        elif ret == -1:
            #已经登录
            string = "{id: -1 ,errormsg:\""+ local.String.SKT_LG_ER_alreadyloggedin+"\"}"
            self.write_message(string)
        elif ret == -2:
            #socket已经连接
            string = "{id: -1 ,errormsg:\""+ local.String.SKT_LG_ER_socketreconnect+"\"}"
            self.write_message(string)
        logger.debug('['+self.remote_ip+']  >'+string)
    
    def on_register(self , item):
        username = item['username']
        password = item['password']
        email = item['email']
        ret = database.DB.register(username,password,email)
        string = "{id:"+str(ret[0]) +",errormsg:\""+ret[1]+"\"}"
        self.write_message(string)
    
    def on_close(self):
        logger.debug('['+self.remote_ip+']  disconnected')
        game.core.userLogoff(self.socket_id)
